<template>
  <div>
    <div ref="chart01"></div>

    <a-button @click="dl()">下载图片</a-button>
<br/>
    图片Base64： {{ imgData }}
<br/><br/>
    <a-button @click="drawImg()">生成图片</a-button>

    <div ref="staticImg"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";

const chart01 = ref();
const imgData = ref("");
var myChart;
onMounted(function () {
  myChart = echarts.init(chart01.value, null, {
    width: 600,
    height: 400,
  });

  const option = {
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
      },
    ],
  };

  myChart.setOption(option);
});

const dl = function () {
  //  let mycanvas=document.getElementsByTagName('canvas')[0]
  //   let image=mycanvas.toDataURL("image/png");

  let image = myChart.getDataURL({
    pixelRatio: 2,
    backgroundColor: "#fff",
  });
  let $a = document.createElement("a");
  $a.setAttribute("href", image);
  $a.setAttribute("download", "echarts图片下载.png");
  $a.click();

  imgData.value = image;
};

// 将base64转为blob
function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

const staticImg = ref();

function drawImg() {

    const img = new Image();
    img.src = "https://echarts.apache.org/zh/images/logo.png";


  const canvas = document.createElement("canvas");
  staticImg.value.appendChild(canvas)
  canvas.width = 400;
  canvas.height = 600;
  const context = canvas.getContext("2d");

  context.drawImage(img, 10, 10);
}
</script>

<style></style>
